package com.zxl.always.on.display.ui.helper;

import android.content.Context;
import android.os.PowerManager;

import com.zxl.always.on.display.ApplicationHelper;

import static android.content.Context.POWER_SERVICE;

/**
 * Created by Administrator on 2018/2/24.
 */

public class WakeLockHelper {

    private static final String WAKE_LOCK_TAG = "ScreenOnWakeLock";

    private PowerManager.WakeLock stayAwakeWakeLock;

    public WakeLockHelper(Context context) {
        stayAwakeWakeLock = ((PowerManager) context.getApplicationContext().getSystemService(POWER_SERVICE)).newWakeLock(268435482, WAKE_LOCK_TAG);
        stayAwakeWakeLock.setReferenceCounted(false);
    }

    public void acquire() {
        if (!stayAwakeWakeLock.isHeld()) {
            stayAwakeWakeLock.acquire();
        }
    }

    public void release() {
        if (stayAwakeWakeLock.isHeld()) {
            stayAwakeWakeLock.release();
        }
    }


    public static void turnScreenOn(Context c) {
        try {
            final PowerManager.WakeLock wl = ((PowerManager) c.getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, WAKE_LOCK_TAG);
            wl.acquire();
            ApplicationHelper.postUiThreadDelayed(new Runnable() {
                @Override
                public void run() {
                    wl.release();
                }
            }, 800);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
